#ifndef VERTEX_MANAGERS_H

#include <windows.h>

template <class PixelFormatClass, unsigned int FVF>
class __declspec(dllexport) VertexBuffer
{	
	LPDIRECT3DVERTEXBUFFER9 m_pVertexBuffer;

	static const UINT VB_SIZE = 400;
	LPDIRECT3DDEVICE9 m_pDev;

public:

	bool Create(LPDIRECT3DDEVICE9 pDev)
	{
		m_pDev = pDev;
		
		HRESULT hr = m_pDev->CreateVertexBuffer(VB_SIZE * sizeof(PixelFormatClass),
			D3DUSAGE_WRITEONLY,
			FVF,
			D3DPOOL_MANAGED,
			&m_pVertexBuffer,
			NULL);

		return SUCCEEDED(hr);
	}
	
	void Bind()
	{
		m_pDev->SetFVF(FVF);
		m_pDev->SetStreamSource(0, m_pVertexBuffer, 0, sizeof(PixelFormatClass));
	}

	bool Draw(PixelFormatClass* pVertexColection, USHORT vertexCount, USHORT primitiveCount)
	{
		void* pVertices;

	    HRESULT	hr = m_pVertexBuffer->Lock(0,VB_SIZE * sizeof(PixelFormatClass),&pVertices,0);

		if (FAILED(hr))
			return false;

		memcpy(pVertices,pVertexColection,sizeof(PixelFormatClass) * vertexCount); 
		m_pVertexBuffer->Unlock();  

		m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,0,0,vertexCount,0,primitiveCount);
	
		return true;
	}
};

class __declspec(dllexport) IndexBuffer
{
	LPDIRECT3DINDEXBUFFER9 m_pIndexBuffer;

	static const USHORT IB_SIZE = 400;

	LPDIRECT3DDEVICE9 m_pDev;

public:

	bool Create(LPDIRECT3DDEVICE9 pDev)
	{
		m_pDev = pDev;
		
		HRESULT hr = m_pDev->CreateIndexBuffer(IB_SIZE * sizeof(USHORT),
			D3DUSAGE_WRITEONLY,
			D3DFMT_INDEX16,
			D3DPOOL_MANAGED,
			&m_pIndexBuffer,
			NULL);

		return SUCCEEDED(hr);
	}
	
	void Bind()
	{
		m_pDev->SetIndices(m_pIndexBuffer);
	}


	bool Draw(USHORT* pIndexColection, USHORT indexCount)
	{
		void* pIndices; 

		HRESULT hr = m_pIndexBuffer->Lock( 
			0,							// Fill from start of the buffer
			IB_SIZE * sizeof(USHORT),	// Size of the data to load
			&pIndices,					// Returned index data
			0 );						// Send default flags to the lock

		if (FAILED(hr))
			return false;
		
		memcpy(pIndices,pIndexColection,indexCount * sizeof(USHORT));
		m_pIndexBuffer->Unlock();
		
		return true;
	}
};

#endif